package cn.ella.netty;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

import cn.hutool.json.JSONObject;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NettyClient {
	
	public void start(String serverIp, int serverPort, int clientPort, String clientContextPath, String webPath, String appName) {
		clientContextPath = (clientContextPath == null || clientContextPath == "") ? "/" : clientContextPath;
		webPath = (webPath == null || webPath == "") ? "/ella/health" : webPath;
		JSONObject obj = new JSONObject();
		obj.set("clientPort", clientPort);
		obj.set("clientContextPath", clientContextPath);
		obj.set("webPath", webPath);
		obj.set("appName", appName);
		start(new InetSocketAddress(serverIp, serverPort), obj);
	}
	
	public void start(InetSocketAddress addr, JSONObject obj) {
		EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap()
                .group(group)
                //该参数的作用就是禁止使用Nagle算法，使用于小数据即时传输
                .option(ChannelOption.TCP_NODELAY, true)
                .channel(NioSocketChannel.class)
                .handler(new NettyClientInitializer());

        try {
            ChannelFuture future = bootstrap.connect(addr.getHostName(), addr.getPort()).sync();
            //发送消息
            while(future.channel().isActive()) {
        		future.channel().writeAndFlush(obj.toString()+"\r\n");
        		TimeUnit.SECONDS.sleep(5);
            }
            // 等待连接被关闭
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }
    }
	
	public static void main(String[] args) {
	}
	
}
